﻿using System;
using System.Collections.Generic;
using ApplicationGenerator.Forms.WebControls;
using Castle.ActiveRecord;

namespace ApplicationGenerator.Forms.Utilities
{
    /// <summary>
    /// Register .net types connected with BaseMappedControl types
    /// </summary>
    public class ControlTypeComparer
    {
        IDictionary<Type, IList<Type>> _mappings;

        public ControlTypeComparer()
        {
            _mappings = new Dictionary<Type, IList<Type>>();

            RegisterType(typeof(CheckBoxControl), typeof(bool));
            RegisterType(typeof(TextBoxControl), typeof(int));
            RegisterType(typeof(TextBoxControl), typeof(float));
            RegisterType(typeof(TextBoxControl), typeof(double));
            RegisterType(typeof(TextBoxControl), typeof(decimal));
            RegisterType(typeof(TextBoxControl), typeof(string));
            RegisterType(typeof(TextBoxControl), typeof(DateTime));
        }

        public void RegisterType(Type baseMappedControlType, Type dotNetType)
        {
            if (!_mappings.Keys.Contains(baseMappedControlType))
            {
                _mappings[baseMappedControlType] = new List<Type>();
            }

            _mappings[baseMappedControlType].Add(dotNetType);
        }


        public bool AreValidTypes(Type baseMappedControlType, Type dotNetType)
        {
            if (_mappings.Keys.Contains(baseMappedControlType))
            {
                return _mappings[baseMappedControlType].Contains(dotNetType);
            }

            if (baseMappedControlType == typeof(SetRelationControl))
            {
                return typeof(ActiveRecordBase).IsAssignableFrom(dotNetType);
            }

            if (baseMappedControlType == typeof(SetListControl))
            {
                if (dotNetType.GetGenericArguments().Length == 0)
                {
                    return false;
                }

                return typeof(ActiveRecordBase).IsAssignableFrom(dotNetType.GetGenericArguments()[0]);
            }



            if (baseMappedControlType == typeof(DropDownListControl))
            {
                return dotNetType.IsEnum;
            }

            return false;
        }
    }
}
